import React, {Component} from 'react';
// 导入路由
import { Route} from 'react-router-dom'
// 导入 TabBar
import {TabBar} from 'antd-mobile'
import {HomeOutlined, VideoCameraOutlined, SoundOutlined, UserOutlined} from '@ant-design/icons'

// 导入四大基本布局页面
import Home from "./Home/Home";
import About from "./About/About";
import Movie from "./Movie/Movie";
import News from "./News/News";
import './Layout.scss'

// TabBar 数据
const tabItems = [
    {
        title: '首页',
        icon: <HomeOutlined/>,
        path: '/home'
    },
    {
        title: '电影',
        icon: <VideoCameraOutlined/>,
        path: '/movie'
    },
    {
        title: '新闻',
        icon: <SoundOutlined/>,
        path: '/news'
    },
    {
        title: '个人中心',
        icon: <UserOutlined/>,
        path: '/about'
    }
]

class Layout extends Component {
    state = {
        // 默认选中的TabBar菜单项
        selectedTab: this.props.location.pathname === "/" ? "/home" : this.props.location.pathname
    }
    componentDidUpdate(prevProps, prevState, snapshot) {
        // prevProps 上一次的props，此处也就是上一次的路由信息
        // this.props 当前最新的props，此处也就是最新的路由信息
        if (prevProps.location.pathname !== this.props.location.pathname) {
            // 此时，就说明路由发生切换了
            this.setState({
                selectedTab: this.props.location.pathname
            })
        }
    }

    // 渲染 TabBar.Item
    renderTabBarItem() {
        return tabItems.map(item => (
            <TabBar.Item
                title={item.title}
                key={item.title}
                icon={item.icon}
                selectedIcon={item.icon}
                selected={this.state.selectedTab === item.path}
                onPress={() => {
                    this.setState({
                        selectedTab: item.path
                    })
                    this.props.history.push(item.path)
                }}
            />
        ))
    }

    render() {
        return (
            <div className="layout">
                {/* 2.3 渲染子路由 */}
                <Route path="/home" component={Home}/>
                <Route path="/movie" component={Movie}/>
                <Route path="/news" component={News}/>
                <Route path="/about" component={About}/>
                <TabBar tintColor="#F04742" noRenderContent={true} barTintColor="white">
                    {this.renderTabBarItem()}
                </TabBar>
            </div>
        )
    }
}

export default Layout;
